package com.sfy.sfypicturebackend.controller;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sfy.sfypicturebackend.annotation.AuthCheck;
import com.sfy.sfypicturebackend.common.BaseResponse;
import com.sfy.sfypicturebackend.common.DeleteRequest;
import com.sfy.sfypicturebackend.common.ErrorCode;
import com.sfy.sfypicturebackend.common.ResultUtils;
import com.sfy.sfypicturebackend.constant.UserConstant;
import com.sfy.sfypicturebackend.exception.BusinessException;
import com.sfy.sfypicturebackend.exception.ThrowUtils;
import com.sfy.sfypicturebackend.model.dto.picture.PictureEditRequest;
import com.sfy.sfypicturebackend.model.dto.picture.PictureQueryRequest;
import com.sfy.sfypicturebackend.model.dto.picture.PictureUpdateRequest;
import com.sfy.sfypicturebackend.model.dto.space.SpaceEditRequest;
import com.sfy.sfypicturebackend.model.dto.space.SpaceQueryRequest;
import com.sfy.sfypicturebackend.model.dto.space.SpaceUpdateRequest;
import com.sfy.sfypicturebackend.model.entity.Picture;
import com.sfy.sfypicturebackend.model.entity.Space;
import com.sfy.sfypicturebackend.model.entity.User;
import com.sfy.sfypicturebackend.model.enums.PictureReviewStatusEnum;
import com.sfy.sfypicturebackend.model.vo.picture.PictureVO;
import com.sfy.sfypicturebackend.model.vo.space.SpaceVO;
import com.sfy.sfypicturebackend.service.SpaceService;
import com.sfy.sfypicturebackend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RequestMapping("/space")
@RestController
public class SpaceController {
    
    @Resource
    private UserService userService;
    
    @Resource
    private SpaceService spaceService;

    /**
     * 删除空间
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest,
                                               HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long id = deleteRequest.getId();
        Space spaceById = spaceService.getById(id);
        // 只有本人和管理员能删除
        if (!spaceById.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
        }
        boolean res = spaceService.removeById(id);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 更新空间(仅管理员)
     *
     * @param spaceUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest
            , HttpServletRequest request) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        // 自动填充数据
        spaceService.fillSpaceBySpaceLevel(space);
        spaceService.validSpace(space,false);
        // 判断是否存在
        Long id = space.getId();
        Space spaceServiceById = spaceService.getById(id);
        if (spaceServiceById == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        spaceService.fillSpaceBySpaceLevel(space);
        // 修改
        boolean res = spaceService.updateById(space);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取空间(仅管理员)
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getPictureById(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限");
        }
        Space spaceServiceById = spaceService.getById(id);
        return ResultUtils.success(spaceServiceById);
    }

    /**
     * 根据id获取空间VO
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getPictureVOById(Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id == null || id <= 0, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(id);
        SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
        return ResultUtils.success(spaceVO);
    }

    /**
     * 分页获取空间列表（仅管理员可用）
     *
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listspaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间列表(封装类)
     *
     * @param spaceQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listspaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                             HttpServletRequest request) {
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        // 普通用户只能查看过审的空间
        Page<Space> spacePage = spaceService.page(new Page<>(current, pageSize),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }

    /**
     * 编辑空间（给用户使用）
     *
     * @param spaceEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editspace(@RequestBody SpaceEditRequest spaceEditRequest,
                                             HttpServletRequest request) {
        if (spaceEditRequest == null || spaceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        spaceService.editSpace(spaceEditRequest, request);
        return ResultUtils.success(true);
    }

}
